//
//  WBToolsHttp.m
//  微博项目
//
//  Created by huangchucai on 16/2/18.
//  Copyright © 2016年 com.foxconn.FuLearn. All rights reserved.
//

#define  timeOutInterval 15
#import "HttpTool.h"
//#import "AFNetworking.h"
//#import "AFHTTPRequestOperationManager.h"
#import <AFNetworking.h>
//#import <AFHTTPRequestOperationManager.h>
//#import "WBUploadParam.h"

@implementation NSDictionary (Convert)
- (NSString *)dictToJson{
    
    NSData *dictData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:nil];
    return [[NSString alloc]initWithData:dictData encoding:NSUTF8StringEncoding];

}
@end


@interface HttpTool ()

@property(nonatomic,assign)BOOL isStatusReachable;

@end


@implementation HttpTool

+ (void)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
//    [MBProgressHUD showMessage:@"加载数据..." toView:WBKeyWindow];
    //增加这几行代码；  
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];   [securityPolicy setAllowInvalidCertificates:YES];
    
    //创建一个请求管理器    
//    AFHTTPRequestOperationManager  *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
    
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    manager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
    
    //由于AFN是不支持text/html的数据格式的，此时服务返回text/html
    manager.responseSerializer = [[AFCompoundResponseSerializer alloc] init];
    
    // 设置网络链接超时的时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = timeOutInterval ;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];

    [manager GET:URLString parameters:parameters
         headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // responseObject ---> NSData   ---> Array&Dict ["1":"2"]  "null"
   
//        [MBProgressHUD hideHUDForView:WBKeyWindow animated:YES];

       //先把请求成功要做的事情，保存的下面的代码块中。
       //success block的定义由外部传入
       if (success)
       {
           //解释JSONO
           id   responseObj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
           
//            [MBProgressHUD hideHUDForView:WBKeyWindow animated:YES];
           
           //解释字符串
           NSData*data =(NSData*)responseObject;
           NSString  *resultString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
           
           //如果是数组或者字典，返回数组或者字典；
           if (responseObj)
           {
              success(responseObj);
              
           }else
           {
           //如果是字符串，返回字符串；
               success(resultString);
           }
       }
    
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            failure(error);
        }
    }];

}

+ (void)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    //[MBProgressHUD showMessage:@"加载数据..." toView:WBKeyWindow];

    AFHTTPSessionManager  *manager  =  [AFHTTPSessionManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];   [securityPolicy setAllowInvalidCertificates:YES];      
    [manager setSecurityPolicy:securityPolicy];  
    
    //由于AFN是不支持text/html的数据格式的，此时服务返回text/html
    manager.responseSerializer = [[AFCompoundResponseSerializer alloc] init];
    
    // 设置网络超时的时间
    // 设置网络链接超时的时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = timeOutInterval ;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [manager POST:URLString parameters:parameters  headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        
//        [MBProgressHUD hideHUDForView:WBKeyWindow animated:YES];

        if (success) {
            
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
//        [MBProgressHUD showError:@"数据加载失败" toView:WBKeyWindow];
//        [MBProgressHUD hideHUDForView:WBKeyWindow animated:YES];
        
        if (failure) {
            failure(error);
        }
    }];
}

//+ (void)Upload:(NSString *)URLString
//    parameters:(id)parameters
//   uploadParam:(WBUploadParam *)uploadParam
//       success:(void (^)(id responseObject))success
//       failure:(void (^)(NSError *error))failure
//{
//    AFHTTPSessionManager  *manager  =  [AFHTTPSessionManager manager];
//    
//    //由于AFN是不支持text/html的数据格式的，此时服务返回text/html
//    manager.responseSerializer = [[AFCompoundResponseSerializer alloc] init];
//    
//    // 设置网络超时的时间
//    // 设置网络链接超时的时间
//    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
//    manager.requestSerializer.timeoutInterval = timeOutInterval ;
//    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
//    
//    [manager POST:URLString parameters:parameters  headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//    }];
//    
//}

+ (void)PostNSURLConnection:(NSString *)URLString
            parameterString:(NSString *)paramString
                    success:(void (^)(id  responseObject))success
                    failure:(void (^)(NSError *error))failure
{
    // 请求参数    
    //NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]];
    NSMutableURLRequest  *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:URLString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:Request_Timeout];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [paramString dataUsingEncoding:NSUTF8StringEncoding];
    NSOperationQueue *queue=[NSOperationQueue mainQueue];    
    // 发出异步请求
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        // 成功的返回    
        if(data){
        
        success(data);
        
        }
        // 失败的返回
        else if (connectionError) {
            
            failure(connectionError);
        }
    }];
}

/**
 *  自己用NSURLConnection封装的一个postXML请求，用于返回值(NSXMLParser *)parser时的情况
 *
 *  @param URLString  请求的URL地址字符串
 *  @param parameters 参数列表
 *  @param success    请求成功的返回
 *  @param failure    请求失败的返回
 */
+(void)postXMLNSURLConnection:(NSString *)URLString
              parameterString:(NSString *)paramString
                      success:(void (^)(id  responseObject))success
                      failure:(void (^)(NSError *error))failure
{
    
//    NSURL *url = [NSURL URLWithString:URLString];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[paramString length]];
//    [request addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//    [request addValue:URLString forHTTPHeaderField:@"SOAPAction"];
//    [request addValue: msgLength forHTTPHeaderField:@"Content-Length"];
//    [request setHTTPMethod:@"POST"];
//    [request setTimeoutInterval:Request_Timeout];
//    [request setHTTPBody: [paramString dataUsingEncoding:NSUTF8StringEncoding]];
//    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//    operation.responseSerializer = [AFXMLParserResponseSerializer serializer];
//    
//    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
//     {
//         //返回值(NSXMLParser *)parser
//         success(responseObject);
//         
//     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
//    {
//         DebugLog(@"%@",error);
//         failure(error);
//     }];
//    
//    [operation start];

}

//判断网络是否可靠
+(void)aFNetworkReachabilityStatusNotReachablesuccess:(void (^)(id responseObject))success failure:(void (^)(NSString *error))failure
{
    //初始值为NO;
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
    {
        NSLog(@"%ld",(long)status);
    
        if (status ==AFNetworkReachabilityStatusReachableViaWiFi)
        {
            NSLog(@"WiFi网络");
            success(@"yes");
            
        }else if (status ==AFNetworkReachabilityStatusReachableViaWWAN)
        {
           NSLog(@"手机4G自带网络");
           success(@"yes");
        }else
        {
           NSLog(@"没有连接网络");
           failure(@"NO");
        }
    }];

    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
}


//实时监测网络
+(void)checkRunTimeNetworkStatusSuccess:(void (^)(id responseObject))success failure:(void (^)(NSString *error))failure
{
    //初始值为NO;
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
    {
        if (status ==AFNetworkReachabilityStatusReachableViaWiFi||status ==AFNetworkReachabilityStatusReachableViaWWAN)
        {
            NSLog(@"WiFi网络");
            success(@"yes");
        }else
        {
           NSLog(@"没有连接网络");
           failure(@"NO");
        }
    }];
}




@end
